
package com.work.mvc.view.tree;

import java.io.Serializable;
import java.util.List;

import com.vaadin.data.Item;
import com.vaadin.data.util.HierarchicalContainer;
import com.work.jaxb.menu.*;

public class MenuTreeFactory implements Serializable {

	private static final long serialVersionUID = -4419248361750289894L;

	private static MenuTreeFactory menuTreeFactory = null;

	protected MenuTreeFactory() {}

	public static MenuTreeFactory getInstance()
	{
		if (menuTreeFactory == null) {
			menuTreeFactory = new MenuTreeFactory();
		}
		return menuTreeFactory;
	}

	public HierarchicalContainer createTreeContent(XmlMenu menu, List<XmlPropertyEnum> propertyTypes)
	{
		HierarchicalContainer treeContainer = new HierarchicalContainer();

		for (XmlPropertyEnum property : propertyTypes) {
			treeContainer.addContainerProperty(property.getValue(), property.getType(), null);
		}

		for (XmlOption option : menu.getOptions()) {
			createTreeOption(option, null, treeContainer);
		}
		
		return treeContainer;
	}

	public void createTreeOption(XmlOption menuOption, String parentId, HierarchicalContainer container)
	{
		String id = menuOption.getId();
		Item item = container.addItem(id);
		
		if (parentId != null) {
			container.setParent(id, parentId);
		}

		for (XmlOptionProperty optionProperty : menuOption.getProperties()) {
			String propertyName = optionProperty.getName().getValue();
			Object propertyValue = optionProperty.getValue();

			item.getItemProperty(propertyName).setValue(propertyValue);
		}

		if (menuOption.getOptions() == null || menuOption.getOptions().isEmpty()) {
			container.setChildrenAllowed(id, false);
		} else {
			container.setChildrenAllowed(id, true);
			for (XmlOption subOption : menuOption.getOptions()) {
				createTreeOption(subOption, id, container);
			}
		}
	}

}
